﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;

namespace ChatGPT_SerialPortDemo.Bussinesses
{
    public class SerialPortManager
    {
        private SerialPort _serialPort;
        private bool _isConnected = false;

        public bool IsConnected
        {
            get { return _isConnected; }
            private set { _isConnected = value; }
        }


        public delegate void DataReceivedEventHandler(object sender, byte[] data);
        public event DataReceivedEventHandler DataReceived;

        public delegate void ConnectionStateChangedEventHandler(object sender, bool flag);
        public event ConnectionStateChangedEventHandler ConnectionStateChanged;

        public SerialPortManager()
        {
            _serialPort = new SerialPort();
            _serialPort.DataReceived += SerialPort_DataReceived;
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = _serialPort.BytesToRead;
            byte[] recvDat = new byte[len];

            _serialPort.Read(recvDat, 0, len);

            DataReceived?.Invoke(this, recvDat);
        }

        public bool Connect(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake)
        {
            try
            {
                _serialPort.PortName = portName;
                _serialPort.BaudRate = baudRate;
                _serialPort.Parity = parity;
                _serialPort.DataBits = dataBits;
                _serialPort.StopBits = stopBits;
                _serialPort.Handshake = handshake;

                _serialPort.Open();
                IsConnected = true;
                OnConnectionStateChanged(true);

                return true;
            }
            catch (Exception ex)
            {
                // 处理异常
                return false;
            }
        }

        public void Disconnect()
        {
            if (IsConnected)
            {
                _serialPort.Close();
                IsConnected = false;
                OnConnectionStateChanged(false);
            }
        }
        private void OnConnectionStateChanged(bool isConnected)
        {
            var handler = ConnectionStateChanged;
            ConnectionStateChanged?.Invoke(this, isConnected);
        }

        public bool SendData(string data)
        {
            bool isSuccess = _isConnected && _serialPort.IsOpen;
            if (isSuccess)
            {
                _serialPort.Write(data);
            }
            return isSuccess;
        }

        public bool SendData(byte[] data)
        {
            bool isSuccess = _isConnected && _serialPort.IsOpen;
            if (isSuccess)
            {
                _serialPort.Write(data, 0, data.Length);
            }
            return isSuccess;
        }
    }
}
